package o2o.task.order;


import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.sys.SysCustomerCache;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.order.ORDER_TYPE;
import o2o.dao.PO.order.OrderInfo;
import o2o.dao.PO.policy.PolicyInfo;
import o2o.service.order.other.OtherOrderService;
import o2o.system.data.SYS_SETTINGS;
import o2o.web.actions.order.OrderCommentMan;
import o2o.web.actions.service.MarketingOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class OrderTask {

    @Autowired
    private MarketingOrderService marketingOrderService;

    @Autowired
    private OtherOrderService otherOrderService;

    // 收藏骑手优先抢单
    @Scheduled(cron = "*/30 * * * * ?")   //每30秒执行一次
    public void checkSpecifiedPostmen() {
        if (SYS_SETTINGS.POSTMAN_LIKE_IS_FIRST != null && SYS_SETTINGS.POSTMAN_LIKE_IS_FIRST == 1
                && SYS_SETTINGS.LIKE_POSTMAN_UNROB_TIME != null && SYS_SETTINGS.LIKE_POSTMAN_UNROB_TIME > 0) {
            List<OrderInfo> orderInfoList = OrderInfoMemory.getInstance().getAllUnDeliveryListAndIsSpecifiedPostmen();
            if (ValidateUtil.isAbsList(orderInfoList)) {
                OrderTaskUtil.checkPostManLikeList.addAll(orderInfoList);
                OrderTaskUtil.checkOrder();
            }
        }
    }

    // 订单超时记录订单
    @Scheduled(cron = "0/30 * *  * * ? ")   //每30秒执行一次
    public void orderOverTimeCheck() {
        if (SYS_SETTINGS.IS_CHECK_ORDER_OVERTIME != null && SYS_SETTINGS.IS_CHECK_ORDER_OVERTIME == 1) {
            List<OrderInfo> platformIngOrderList = OrderTaskUtil.getPlatformIngOrderList();
            if (ValidateUtil.isAbsList(platformIngOrderList)) {
                OrderTaskUtil.platformIngOrderList.addAll(platformIngOrderList);
                OrderTaskUtil.checkOrderOverTime();
            }
        }
    }


    // 自动派单
    @Scheduled(cron = "0/30 * *  * * ? ")   //每30秒执行一次
    public void dispatchOrder() {
        // todo 按商圈自动派单
        // 自动派单
        OrderTaskUtil.dispatchOrder();
    }

    //    // 检测聚合订单 商家接单
    @Scheduled(cron = "0/30 * *  * * ? ")   //每5秒执行一次
    public void checkMultipleOrder() {

        // 检测聚合订单 商家接单
        OrderTaskUtil.checkMultipleOrder();
    }


    // 未接单商家，给予电话通知
    @Scheduled(cron = "0/30 * *  * * ? ")   //每5秒执行一次
    public void noticeShopNewOrder() {
        // 未接单商家，给予电话通知
        if (null == SYS_SETTINGS.SHOP_NEW_ORDER_PHONE || SYS_SETTINGS.SHOP_NEW_ORDER_PHONE < 1) {
            return;
        }
        // 未接单商家，给予电话通知
        OrderTaskUtil.noticeShopNewOrder();
    }

    // 系统订单自动好评
    @Scheduled(cron = "0 0 1 * * ?") // 每天的凌晨一点执行一次
    public void systemOrderAutoComment() {
        if (SYS_SETTINGS.ORDER_COMMENT_DEFAULT_DAY == null || SYS_SETTINGS.ORDER_COMMENT_DEFAULT_DAY == 0) {
            return;
        }
        try {
            OrderCommentMan.systemOrderAutoComment();
        } catch (Exception e) {
            System.out.println("自动评论失败。。。。。。");
            e.printStackTrace();
        }

    }

    //    // 订单超时记录上传
    @Scheduled(cron = "0/30 * *  * * ? ")    //每30秒执行一次
    public void orderMarkOverTime() {
        List<OrderInfo> platformIngOrderList = OrderInfoMemory.getInstance().listOfIngPlatFormOrderList();
//        List<OrderInfo> platformIngOrderList = OrderTaskUtil.getPlatformIngOrderList();
        if (ValidateUtil.isAbsList(platformIngOrderList)) {
            cloudOrderOverTimeMarket(platformIngOrderList);
        }
    }

    //  订单自动完成
    @Scheduled(fixedDelay = 10 * 60 * 1000L)
    // @Scheduled(fixedDelay = 3 * 1000L)
    public void autoOrderDadaQueryStates() {
        if (SYS_SETTINGS.IS_OTHER_POST != null && SYS_SETTINGS.IS_OTHER_POST == 2) {
            System.out.println("哒哒订单自动查询状态执行了~~~");
            OrderTaskUtil.autoOrderDadaQueryStates();
        }
    }


    //  自动骑手转单时间
    @Scheduled(fixedDelay = 60 * 1000L)
    public void autoFinishChangePostman() {
        if (SYS_SETTINGS.AUTO_FINISH_CHANGE_POSTMAN_TIME > 0) {
            OrderTaskUtil.autoFinishChangePostman();
        }
    }


    //
    public synchronized void cloudOrderOverTimeMarket(List<OrderInfo> orderInfoList) {
        if (ValidateUtil.isAbsList(orderInfoList)) {
            for (OrderInfo orderInfo : orderInfoList) {
                marketOrderOverTime(orderInfo);
            }
        }
    }

    public void marketOrderOverTime(OrderInfo orderInfo) {
        if (orderInfo == null) {
            return;
        }
        if (orderInfo.getIsZiQu() == 1
                || ValidateUtil.isNotNull(orderInfo.getMarketOrderOverTime())
                || orderInfo.getOrderType() != ORDER_TYPE.SHOP_GOODS
                || ValidateUtil.isNotID(orderInfo.getShopId())
                || ValidateUtil.isNotAbsLong(orderInfo.getCreateTime())
                || DateUtils.getCurrTime() - orderInfo.getCreateTime() > 2 * 24 * 60 * 60 * 1000L) {
            return;
        }
        boolean isOrderOverTime = false;
        if (orderInfo.getShopSelfPost() != null
                && orderInfo.getShopSelfPost() == 1) {
            // 自配送订单
//            Long payTime = orderInfo.getPayTime();
//            if (!ValidateUtil.isAbsLong(payTime)) {
//                payTime = orderInfo.getCreateTime();
//            }
//            if (ValidateUtil.isAbsLong(orderInfo.getZiQuTime())) {
//                if (ValidateUtil.isAbsLong(orderInfo.getZiQuTime()) && DateUtils.getCurrTime() > orderInfo.getZiQuTime()) {
//                    isOrderOverTime = true;
//                } else {
//                    long time = orderInfo.getAgentOrderOverTime() != null ? orderInfo.getAgentOrderOverTime() * 60 * 1000L : 0L;
//                    if (ValidateUtil.isAbsLong(time)) {
//                        if ((payTime + time) > DateUtils.getCurrTime()) {
//                            isOrderOverTime = true;
//                        }
//                    }
//                }
//            }
        } else {
            Long payTime = orderInfo.getPayTime();
            if (!ValidateUtil.isAbsLong(payTime)) {
                payTime = orderInfo.getCreateTime();
            }
            if (ValidateUtil.isAbsLong(orderInfo.getZiQuTime())) {
                if (ValidateUtil.isAbsLong(orderInfo.getZiQuTime()) && DateUtils.getCurrTime() > orderInfo.getZiQuTime()) {
                    isOrderOverTime = true;
                } else {
                    long time = orderInfo.getAgentOrderOverTime() != null ? orderInfo.getAgentOrderOverTime() * 60 * 1000L : 0L;
                    if (ValidateUtil.isAbsLong(time)) {
                        if ((payTime + time) > DateUtils.getCurrTime()) {
                            isOrderOverTime = true;
                        }
                    }
                }
            }
        }
        if (isOrderOverTime) {
            String sysAppKey = orderInfo.getSysAppKey();
            if (ValidateUtil.isNull(sysAppKey)) {
                sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
            }
            marketingOrderService.deliveryTimeOutWarnNotice(sysAppKey, "", orderInfo.getOrderNo(), orderInfo.getShopId(), orderInfo.getUsername());
            StringBuilder sql = new StringBuilder();
            sql.append(" update ").append(PojoTables.OrderInfo)
                    .append(" set marketOrderOverTime = '1'")
                    .append(" where orderNo = '").append(orderInfo.getOrderNo()).append("'")
                    .append(" and (marketOrderOverTime is null or marketOrderOverTime = '') and delFlag = 0 ");
            try {
                UserDaoSql.getInstance().executeBySql(sql.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            OrderInfoMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
            //
        }
    }

    /**
     * 处理线路车的保险
     */
    @Scheduled(cron = "0 */3 * * * ?")   // 每三分钟执行一次
    public void baoXianCheck() {
        if (SYS_SETTINGS.HAS_BAO_XIAN != null && SYS_SETTINGS.HAS_BAO_XIAN == 1) {
            OrderTaskUtil.dealThreadBaoXian();
        }
    }

    // 处理线路车保险下单到第三方
    @Scheduled(fixedDelay = 15 * 1000L)
    public void baoXianSend() {
        if (SYS_SETTINGS.HAS_BAO_XIAN != null && SYS_SETTINGS.HAS_BAO_XIAN == 1) {
//            Long time = DateUtils.getCurrTime() - 3 * 24 * 60 * 60 * 1000L;
//            /**
//             *  个保
//             */
//            String sql = "select * from " + PojoTables.ORDER_POLICY_RECORD + " WHERE delFlag = 0 and updateTime > " + time + " and status = " + INSURANCE_STATUS.THREAD_ORDER_INSURANCE_STATUS.INSURANCE_SELF_UNDEAL
//                    + " and type = 2";
//            List<PolicyInfo> list = null;
//            try {
//                list = (List<PolicyInfo>) UserDaoSql.getInstance().list(PolicyInfo.class, sql);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            // 未下单的保单信息
            List<PolicyInfo> list = OrderTaskUtil.unDealPolicyList();
            if (ValidateUtil.isAbsList(list)) {
                Map<String, List<PolicyInfo>> listMap = list.stream().collect(Collectors.groupingBy(PolicyInfo::getOrderNo));
                for (String key : listMap.keySet()) {
                    List<PolicyInfo> infoList = listMap.get(key);
                    otherOrderService.sendThreadPolicy(infoList, infoList.get(0).getOrderNo(), "admin");
                }
            }
        }
    }

    // 每天的凌晨 执行一下 查看团购订单的是否已经过期了 如果过期了则取消订单
    //秒  分  时  日  月  星期几  年
    @Scheduled(cron = "0 20 0 * * ?")
    public void groupOrderValidCheck() {
        if (SYS_SETTINGS.GROUP_ORDER_EXPIRED_AUTO_CANCEL != null && SYS_SETTINGS.GROUP_ORDER_EXPIRED_AUTO_CANCEL == 1) {
            OrderTaskUtil.groupOrderExpiredCheck();
        }
    }

}
